package com.factory.rest.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.factory.common.bean.User;
import com.factory.common.bean.UserDevices;
import com.factory.common.core.BaseService;
import com.factory.common.core.SqlCondition;
import com.factory.common.pojo.QueryListParam;
import com.factory.common.pojo.Result;
import com.factory.rest.feign.AiClients;
import com.factory.rest.pojo.UserDevicesPojo;
import com.factory.rest.service.UserDevicesService;
import com.factory.rest.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户设备
 *
 * @author JW
 * @version 1.0
 * @date 2020/10/28 10:49
 */
@RestController
@RequestMapping("/rest/userDevices")
public class UserDevicesController extends BaseController<UserDevicesPojo> {

    @Autowired
    private UserDevicesService userDevicesService;

    @Autowired
    private UserService userService;

    @Autowired
    private AiClients devicesClients;

    @Resource(name = "redisTemplate")
    private RedisTemplate<String, JSONObject> redisTemplate;

    @Override
    protected BaseService getBaseService() {
        return userDevicesService;
    }

    /**
     * 设备数据统计
     *
     * @return
     */
    @GetMapping(value = "/statistics")
    public Result statistics() {
        log.info("设备数据统计");
        User user = userService.getLoginUser().get();

        Map<String, Object> params = new HashMap<>();
        params.put("userId", user.getId());
        Map<String, Object> statistics = userDevicesService.statistics(params);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", user.getId());
        Result result = devicesClients.onLines(jsonObject);

        if (result.isStatus()) {
            statistics.put("onLine", result.getData());
        }

        return Result.success(statistics, "查询成功!");
    }

    @Override
    public Result queryList(@RequestBody QueryListParam param) {
        User user = userService.getLoginUser().get();

        List<SqlCondition> conditions = param.getConditions();
        conditions.add(new SqlCondition("userId", user.getId(), SqlCondition.Conditions.EQ));

        Result result = super.queryList(param);

        IPage iPage = (IPage) result.getData();

        List<UserDevices> records = iPage.getRecords();
        List<UserDevicesPojo> userDevicesPojos = new ArrayList<>();
        ValueOperations<String, JSONObject> stringJSONObjectValueOperations = redisTemplate.opsForValue();
        records.forEach(e -> {
            UserDevicesPojo userDevicesPojo = new UserDevicesPojo();
            BeanUtils.copyProperties(e, userDevicesPojo);
            JSONObject jsonObject = stringJSONObjectValueOperations.get(String.format("Heartbeat-%s", e.getId()));
            if (null != jsonObject) {
                userDevicesPojo.setCpu(jsonObject.getFloat("cpu"));
                userDevicesPojo.setGpu(jsonObject.getFloat("gpu"));
                userDevicesPojo.setMemory(jsonObject.getFloat("memory"));
            }
            userDevicesPojos.add(userDevicesPojo);
        });

        iPage.setRecords(userDevicesPojos);

        return result;
    }

    /**
     * 检查设备是否在线
     *
     * @return
     */
    @GetMapping("/onLine/{deviceId}")
    public Result onLine(@PathVariable String deviceId) {
        return devicesClients.isOnLine(deviceId);
    }


}
